<?php

namespace Common\Model;

use Think\Model;

class patientMedicineCureModel extends Model {

    protected $tableName = 'patient_medicine_cure';

    protected $_validate = array(
        ['car_id', 'require', 'car_id 需要提供', self::MUST_VALIDATE],
        ['patient_id', 'require', 'patient_id 需要提供', self::MUST_VALIDATE],
        ['medicine_list', 'checkMedicinelist', 'medicine_list format error', self::MUST_VALIDATE, 'callback']
    );

    protected $_auto = array(
        ['create_time', 'time', self::MODEL_INSERT, 'function'],
    );

    public function checkMedicinelist($list) {
        if (json_decode($list)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 对病人添加一般治疗手段
     */
    public function addMedicineCure($carId, $patientId, $medicineList) {
        $data = [];
        if (!$this->create()) {
            return ['status' => 0, 'error_info' => $this->getError()];
        }
        //删除之前的数据
        //$this->where(['car_id' => $carId, 'patient_id' => $patientId])->delete();

        $medicineArr = json_decode(htmlspecialchars_decode($medicineList), true);
        foreach ($medicineArr as $medicine) {
            $data = [
                'car_id' => $carId,
                'patient_id' => $patientId,
                'medicine_id' => $medicine['medicine_id'],
                'format' => $medicine['format'],
                'unit' => $medicine['unit'],
                'num' => $medicine['num'],
                'amount' => $medicine['amount'],
                'method' => $medicine['method']
            ];
            if (!$this->create($data)) {
                return ['status' => 0, 'error_info' => $this->getError()];
            }
            $this->add();
        }

        return ['status' => 1];

    }

    public function getAllInfo($patient) {
        return $this->where(['patient_id' => $patient])->select();
    }
}